﻿using System;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;

namespace geopg_wp7
{
    public partial class RegisterPage : PhoneApplicationPage
    {

        public RegisterPage()
        {
            InitializeComponent();
        }

        // Same procedure as in LoginPage
        void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            // Dispatcher fixes SystemAuthorizationException for string postData
            this.Dispatcher.BeginInvoke(delegate()
            {
                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                System.IO.Stream postStream = request.EndGetRequestStream(asynchronousResult);
                string postData = "user=" + user_box.Text + "&password=" + password_box.Password + "&email=" + email_box.Text;
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);
                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();
                request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
            });
        }

        void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                HttpWebResponse response;
                response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
                System.IO.Stream streamResponse = response.GetResponseStream();
                System.IO.StreamReader streamReader = new System.IO.StreamReader(streamResponse);
                string responseString = streamReader.ReadToEnd();
                Console.WriteLine(responseString);
                this.Dispatcher.BeginInvoke(delegate()
                {
                    // Output is the position of the string. If it doesn't exist, its position is "-1"
                    if (responseString.IndexOf("cause") != -1)
                    {
                        if (responseString.IndexOf("cause=\"0\"") != -1)
                            MessageBox.Show("Internal Error (SQL)");
                        else if (responseString.IndexOf("cause=\"1\"") != -1)
                            MessageBox.Show("Expected POST but got GET request.");
                        else if (responseString.IndexOf("cause=\"10\"") != -1)
                            MessageBox.Show("Please enter a username.");
                        else if (responseString.IndexOf("cause=\"11\"") != -1)
                            MessageBox.Show("Please enter a password.");
                        else if (responseString.IndexOf("cause=\"12\"") != -1)
                            MessageBox.Show("Please enter an E-mail.");
                        else if (responseString.IndexOf("cause=\"17\"") != -1)
                            MessageBox.Show("Invalid user syntax.");
                        else if (responseString.IndexOf("cause=\"21\"") != -1)
                            MessageBox.Show("Invalid password syntax.");
                        else if (responseString.IndexOf("cause=\"19\"") != -1)
                            MessageBox.Show("Invalid E-mail syntax.");
                        else if (responseString.IndexOf("cause=\"18\"") != -1)
                            MessageBox.Show("Username " + user_box.Text + " already exists.");
                        else if (responseString.IndexOf("cause=\"20\"") != -1)
                            MessageBox.Show("E-mail address with " + email_box.Text + " already exists.");
                        else if (responseString.IndexOf("cause=\"4\"") != -1)
                            MessageBox.Show("Not enough privileges to perform action.");
                        else
                            MessageBox.Show("Unexpected Error");
                        // More Error-Codes to be done!
                    }
                    else
                    {
                        MessageBox.Show("Registration successful.");
                        // TODO: AutoLogin after registration is complete!
                        NavigationService.Navigate(new Uri("//LoginPage.xaml", UriKind.Relative));
                    }
                });
                streamResponse.Close();
                streamReader.Close();
                response.Close();
            }
            catch (WebException e)
            {
                this.Dispatcher.BeginInvoke(delegate()
                {
                    MessageBox.Show("Can't establish connection.");
                });
            }
        }

        void registerButton_Click(object sender, EventArgs e)
        {
            if (rePassword_box.Password == password_box.Password)
            {
                Uri address = new Uri("http://geopg.de/backend/UserReg");
                HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
            }
            else
                MessageBox.Show("The passwords didn't match.");
        }

        private void mainPage_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//MainPage.xaml", UriKind.Relative));
        }

        private void localPictures_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//LocalPicturesPage.xaml", UriKind.Relative));
        }

        private void settings_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//SettingsPage.xaml", UriKind.Relative));
        }

        private void info_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//InfoPage.xaml", UriKind.Relative));
        }

        private void passwordBox1_PasswordChanged(object sender, RoutedEventArgs e)
        {

        }
    }
}